import sys
from socket import *
from time import sleep

FTP = "/home/tarena/FTP/"

class FTPController:
    def __init__(self,sock):
        self.sock = sock

    def select(self):
        self.sock.send(b'LIST ')
        result = self.sock.recv(128)
        if result == b'OK':
            data = self.sock.recv(1024*1024*10)
            print(data.decode())
        else:
            print(result.decode())

    def download(self,filename):
        msg = "RETR " + filename
        self.sock.send(msg.encode())
        result = self.sock.recv(128)
        if result == b'OK':
            # 接收文件
            fw = open(filename, 'wb')
            while True:
                data = self.sock.recv(1024)
                fw.write(data)
                if data == b"##":
                    break
            fw.close()
        else:
            print(result.decode())


    def upload(self,filename):
        # 验证 文件是否正确
        try:
            fr = open(filename, 'rb')
        except:
            print('找不到该文件')
            return
        filename = filename.split("/")[-1]
        msg = "STOR " + filename
        self.sock.send(msg.encode())
        result = self.sock.recv(128)
        if result == b'OK':
            # 发送文件
            while True:
                data = fr.read(1024)
                if not data:
                    break
                self.sock.send(data)
            fr.close()
            sleep(0.1)  # 防止粘包
            self.sock.send(b'##')
            print("上传成功！")
        else:
            print(result.decode())


    def exit(self):
        self.sock.close()
        sys.exit("谢谢使用")

class FTPView:
    def __init__(self,sock):
        self.sock = sock
        self.__controller = FTPController(self.sock)

    def main(self):
        while True:
            self.__display_menu()
            self.__select_menu()

    def __display_menu(self):
        print("""
        =============  FTP文件服务  ============
        1.查看文件   2.下载文件  3.上传文件  4.退出
        =======================================
        """)

    def __select_menu(self):
        item = input("请输入选项:")
        if item == "1":
            self.__controller.select()
        elif item == "2":
            filename = input("要下载的文件：")
            self.__controller.download(filename)
        elif item == "3":
            filename = input("要上传的文件：")
            self.__controller.upload(filename)
        elif item == "4":
            self.__controller.exit()
        else:
            print("请输入正确选项!")

class FTPClient:
    def __init__(self,host='',port=0):
        self.host = host
        self.port = port
        self.address = (self.host, self.port)
        self.sock = self._create_socket()

    def _create_socket(self):
        sock = socket()
        sock.connect(self.address)
        return sock

if __name__ == '__main__':
    ftp_client = FTPClient(host="127.0.0.1", port=12120)
    ftp = FTPView(ftp_client.sock)
    ftp.main()